package homework;

import java.util.HashMap;
import java.util.Map;

//作业标题(2733)
//中序后序还原二叉树
//
//作业内容
//中序后序还原二叉树
//https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/
public class h2733 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    Map<Integer, Integer> Inmap;
    int postIndex;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        Inmap = new HashMap<>();
        postIndex = postorder.length - 1;
        for(int i = 0;  i < inorder.length; i++)
        {
            Inmap.put(inorder[i], i);
        }
        return _buildTree(inorder, postorder, 0, inorder.length - 1);
    }

    private TreeNode _buildTree(int[] inorder, int[] postorder, int Ibegint, int Iend)
    {
        if(Ibegint > Iend) return null;

        TreeNode root = new TreeNode(postorder[postIndex]);
        int index = Inmap.get(postorder[postIndex]);
        postIndex--;
        root.right = _buildTree(inorder, postorder, index + 1, Iend);
        root.left = _buildTree(inorder, postorder, Ibegint, index - 1);

        return root;
    }

}
